package br.ufrj.dcc.tp.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import br.ufrj.dcc.tp.common.Client;
import br.ufrj.dcc.tp.common.Message;

public class ServerThread extends Thread {

	private Client client = null;
	private Socket socket;
	
	static List<Message> messages = new ArrayList<Message>();
		
	public ServerThread(Socket socket) {
		super("Server Thread Message");
		this.socket = socket;
	}
	
	/**
	 * Recebe a mensagem de alguma conex�o e repassa para todos
	 * */
	@Override
	public synchronized void run() {
		
		System.out.println(this.getClass() + " iniciando o método run() ...");
		
		try {
			
			ObjectInputStream in = new ObjectInputStream(
					socket.getInputStream());
			
			Object obj;			
			while((obj = in.readObject()) != null) {
				// recebendo o nome do usuário
				if(obj instanceof Client) {
					// Registra socket
					ServerService.getClientsInstance().put((Client)obj, socket);
					System.out.println(this.getClass() + "Socket registrado!");
					
					ServerService.sendObjectForAllSockets(
								ServerService.getClientsInstance().keySet().toArray());
					in = new ObjectInputStream(socket.getInputStream());
				}
				// se é uma mensagem, envia a todos os clientes
				else if(obj instanceof Message) {
					System.out.println("Recebeu mensagem! Enviando mensagem para todos os sockets ...");
					messages.add((Message)obj);
					System.out.println(this.getClass() + "MENSAGEM: "+ messages.toString());
					ServerService.sendMessageForAllSockets((Message)obj); 
					System.out.println("Mensagem enviada!");
					in = new ObjectInputStream(socket.getInputStream());
							
				} 
				
								
			}
			
			in.close();
			ServerService.getClientsInstance().get(client).close();
			ServerService.getClientsInstance().remove(client);
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println(this.getClass() + "Error while reading object ..");
			e.printStackTrace();
		}
		
	}
	
}
